<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, computed } from 'vue';
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from "vue-router";
import authService from "@/services/auth.service";
import useAuthStore from "@/stores/auth";
import TabbarWrapper from '@/components/TabbarWrapper.vue';
import { showFailToast, showNotify } from 'vant';
import { AxiosError } from "axios";
import personalCenterService from '@/services/personal-center.service';
import dayjs from 'dayjs';

const router = useRouter();

const authStore = useAuthStore();
const { userProfile } = storeToRefs(authStore);
const saveLoading = ref(false);

const entity = ref({});
const datePickerValue = ref([]);
const showDatePicker = ref(false);

const load = async () => {
    try {
        const profile = await personalCenterService.retrieve();
        authStore.setUserProfile(profile);
        entity.value = {
            ...profile.user
        };
        if (entity.value && entity.value.birthday) {
            const date = dayjs(entity.value.birthday);
            datePickerValue.value = [date.year(), date.month(), date.date()];
        }
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
    }
};

onMounted(() => {
    load();
});

const save = async () => {
    try {
        saveLoading.value = true;
        await personalCenterService.update(entity.value);
        load();
        showNotify({
            message: "保存成功", type: "success"
        });
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            showFailToast(msg);
        }
        throw err;
    } finally {
        saveLoading.value = false;
    }
};

const changePassword = async () => {
    router.push("/change-password");
};

const logout = async () => {
    try {
        // 后端注销token
        await authService.logout();
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            showFailToast(msg);
            if (err.response?.data.errorCode == "Auth_Exception_0005") {
                frontLogout();
            }
        }
        throw err;
    } finally {
        frontLogout();
    }
};

const frontLogout = () => {
    // 前端取消授权
    authStore.unAuthenticate();
    // 跳转至主页
    router.push("/");
}

const updateBirthday = (value) => {
    console.log(value);
    showDatePicker.value = false;
    const date = dayjs(value.selectedValues.join(""));
    entity.value.birthday = date.format("YYYY-MM-DD");
    console.log(entity.value.birthday);
}
</script>
<template>
    <div class="page-container absolute left-0 top-0 w-full h-full flex flex-col">
        <div class="header-container">
            <VanNavBar title="个人信息" left-arrow left-text="返回" @click-left="router.back()"></VanNavBar>
        </div>

        <div class="main-container flex-grow">
            <VanForm>
                <VanCellGroup inset>
                    <VanField v-model:model-value="entity.username" name="username" label="用户名" placeholder="用户名" readonly>
                    </VanField>
                    <VanField v-model:model-value="entity.nickname" name="nickname" label="昵称" placeholder="昵称">
                    </VanField>
                    <VanField v-model:model-value="entity.phone" name="phone" label="手机号" placeholder="手机号">
                    </VanField>
                    <VanField v-model:model-value="entity.email" name="email" label="邮箱" placeholder="邮箱">
                    </VanField>
                    <VanField v-model:model-value="entity.realName" name="realName" label="真实姓名" placeholder="真实姓名">
                    </VanField>
                    <VanField v-model:model-value="entity.birthday" name="birthday" label="生日" placeholder="生日" readonly
                        @click="showDatePicker = true">
                    </VanField>
                    <VanPopup v-model:show="showDatePicker" position="bottom">
                        <VanDatePicker v-model:model-value="datePickerValue" @confirm="updateBirthday"></VanDatePicker>
                    </VanPopup>
                    <VanField v-model:model-value="entity.description" name="description" label="个人介绍" placeholder="个人介绍"
                        type="textarea" autosize rows="3" show-word-limit maxlength="100">
                    </VanField>
                </VanCellGroup>
                <VanCellGroup inset>
                    <VanButton round block type="primary" @click="save">
                        保存
                    </VanButton>
                    <VanButton class="mt-2" round block @click="changePassword">
                        修改密码
                    </VanButton>
                    <VanButton class="mt-2" round block @click="logout">
                        退出登录
                    </VanButton>
                </VanCellGroup>
            </VanForm>
        </div>

        <div class="footer-container">
            <TabbarWrapper active-tab="mine"></TabbarWrapper>
        </div>
    </div>
</template>